<template>
    <Popup ref="popupRef" :title="modeTitle" :formState="formState" :rules="rules" :editApi="updateDepartment"
        :addApi="saveDepartment">
        <template #default="{ formState }">
            <a-form-item label="部门名称" name="title">
                <a-input v-model:value="formState.title" placeholder="请输入部门名称" />
            </a-form-item>

            <a-form-item label="组织" name="organization_id">
                <m-form-organize-lists v-model:value="formState.organization_id" />
            </a-form-item>

            <a-form-item label="负责人" name="leader_id">
                <m-form-admin v-model:value="formState.leader_id" />
            </a-form-item>

            {{ formState }}
        </template>
    </Popup>
</template>

<script setup lang="ts">
import Popup from '@/components/popup/index.vue'
import { saveDepartment, updateDepartment } from '@/api/system/organize/department'
const popupRef = ref<InstanceType<typeof Popup>>()
const modes = ref<'add' | 'edit'>('add')

interface FormState {
    id?: number | null
    title: string
    organization_id: string  | null
    leader_id: string | null
}

const formState = reactive<FormState>({
    id: null,
    title: '',
    organization_id: null,
    leader_id: null
})

const rules = {
    title: [{ required: true, message: '请输入部门名称' }],
    organization_id: [{ required: true, message: '请选择组织' }],
    leader_id: [{ required: true, message: '请选择负责人' }]
}

const modeTitle = computed(() => {
    return modes.value === 'add' ? '添加部门' : '编辑部门'
})

const open = (mode: 'add' | 'edit', record?: any) => {
    modes.value = mode

    if (record) {
        for (const key in formState) {
            formState[key] = record[key]
        }
    }

    popupRef.value?.open(mode, formState)
}

defineExpose({
    open
})
</script>
